package indi.mozping.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author by mozping
 * @Classname Util
 * @Description TODO
 * @Date 2019/5/8 15:42
 */
public class SqlSessionFactoryUtil {

    private static SqlSessionFactory factory;

    public static SqlSessionFactory getSqlSessionFactoryInstace() {
        if (factory == null) {
            InputStream in = null;
            try {
                in = Resources.getResourceAsStream("mybatis/mybatis-config-01.xml");
            } catch (Exception e) {
                e.printStackTrace();
            }
            synchronized (SqlSessionFactoryUtil.class) {
                if (factory == null) {
                    factory = new SqlSessionFactoryBuilder().build(in);
                }
            }
        }
        return factory;
    }

    public static SqlSessionFactory getSqlSessionFactoryInstaceByConfig(String filePath) {
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        return factory;
    }

    public static void closeSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

